import { defineStore } from 'pinia';
import { ref } from 'vue';
import * as echarts from 'echarts';
import { FILE_TYPE_COLORS, CHART_CONFIG } from '@/config/constants'

export const useChartStore = defineStore('chart', () => {
  let chartInstance = null;

  // 初始化图表
  const initChart = (container) => {
    if (!container) {
      console.error('Invalid container for ECharts');
      return null;
    }
    
    chartInstance = echarts.init(container);
    return chartInstance;
  };

  // 将依赖数据转换为图表配置
  const convertToChartOption = (data, projects) => {
    const nodes = data.nodes.map(node => ({
      name: node.id,
      value: node.id,
      symbolSize: CHART_CONFIG.node.symbolSize,
      itemStyle: {
        color: getNodeColor(node.type)
      },
      label: {
        show: true,
        formatter: `{a|${node.id}}\n{b|v${node.version}}`,
        rich: {
          a: {
            fontSize: 12,
            lineHeight: 20
          },
          b: {
            fontSize: 10,
            color: '#666'
          }
        }
      }
    }));

    const edges = data.dependencies.map(dep => ({
      source: dep.source,
      target: dep.target
    }));

    return {
      tooltip: {
        trigger: 'item',
        formatter: (params) => {
          if (params.dataType === 'node') {
            const node = data.nodes.find(n => n.id === params.data.name);
            const projectName = getProjectNameById(node.projectId, projects);
            return `${node.id}<br/>版本：v${node.version}<br/>类型：${node.type}<br/>项目：${projectName}`;
          }
          return '';
        }
      },
      series: [{
        type: 'graph',
        layout: 'force',
        data: nodes,
        links: edges,
        force: {
          ...CHART_CONFIG.force,
          initLayout: 'tree'
        },
            // 如果是树形布局，添加额外配置
        orient: 'LR',
        initialTreeDepth: 2,
        edgeShape: 'polyline',
        roam: true,
        draggable: true,
        lineStyle: CHART_CONFIG.edge.lineStyle,
        edgeSymbol: CHART_CONFIG.edge.symbol,
        edgeSymbolSize: CHART_CONFIG.edge.symbolSize,
        emphasis: {
          focus: 'adjacency',
          lineStyle: {
            width: 4
          }
        }
      }]
    };
  };

  // 更新图表数据
  const updateChart = (data, projects) => {
    if (!chartInstance) {
      console.error('Chart not initialized');
      return;
    }
    const option = convertToChartOption(data, projects);
    chartInstance.setOption(option, true);
  };

  // 获取节点颜色
  const getNodeColor = (type) => {
    const fileType = type.split('_')[0].split('.').pop();
    return FILE_TYPE_COLORS[fileType] || '#909399';
  };

  // 获取项目名称
  const getProjectNameById = (projectId, projects) => {
    const project = projects.find(p => p.id === projectId);
    return project ? project.name : '未知项目';
  };

  return {
    initChart,
    updateChart
  };
}); 